﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartCity.EventHandle.API.Write.Application.Commands;
using SmartCity.EventHandle.Domain;
using SmartCity.EventHandle.Errorcode;
using SmartCity.EventHandle.Infrastructure.Commons;
using SmartCity.EventHandle.Infrastructure.Extensions;
using SmartCity.EventHandle.Infrastructure.Interfraces;

namespace SmartCity.EventHandle.API.Write.Application.CommandHandlers
{
    /// <summary>
    /// 应用更新命令处理
    /// </summary>
    public class AppUpdateCommandHandler:IRequestHandler<AppUpdateCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<WF_Instance> instanceRep;
        private readonly IBaseRepository<WF_Record> recordRep;
        private readonly ILogger<AppUpdateCommandHandler> logger;
        private readonly IBaseRepository<WF_Setting> settingRep;

        public AppUpdateCommandHandler(
            IBaseRepository<WF_Instance> instanceRep,
            IBaseRepository<WF_Record> recordRep,
            ILogger<AppUpdateCommandHandler> logger,
            IBaseRepository<WF_Setting> settingRep)
        {
            this.instanceRep = instanceRep;
            this.recordRep = recordRep;
            this.logger = logger;
            this.settingRep = settingRep;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回更新任务</returns>
        public async Task<ApiResult<int>> Handle(AppUpdateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.code = ApiEnum.UpdateSuccess;
            result.message = ApiEnum.UpdateSuccess.GetDescription();

            using(var tran = instanceRep.DB.Database.BeginTransaction())
            {
                try
                {
                    DateTime now = DateTime.Now;
                    #region 更新实例
                    var instance = instanceRep.GetAll().FirstOrDefault(x => x.InstanceId == request.InstanceId);
                    if(instance == null)
                    {
                        throw new Exception("进行了非法操作");
                    }
                    instance.FlowState = (int)FlowStatus.Processing;
                    instance.FlowStateName = FlowStatus.Processing.GetDescription();
                    //特殊情况-当拒绝是,直接结束
                    if(request.ApproveStatus == (int)ApproveStatus.NotPassed)
                    {
                        instance.FlowState = (int)FlowStatus.FiniShed;
                        instance.FlowStateName = FlowStatus.FiniShed.GetDescription();
                    }

                    instance.CurrentNodeNo = instance.NextNodeNo;
                    instance.CurrentNodeName = instance.NextNodeName;
                    instance.CurrentOperatorId = instance.NextOperatorId;
                    instance.CurrentOperatorName = instance.NextOperatorName;

                    //查询流程设置
                    var setting = settingRep.GetAll().FirstOrDefault(x => x.PrevNodeNo == instance.CurrentNodeNo);
                    if(setting == null)
                    {
                        instance.NextNodeNo = "";
                        instance.NextNodeName = "";
                        instance.NextOperatorId = 0;
                        instance.NextOperatorName = "";
                        instance.FlowState = (int)FlowStatus.FiniShed;
                        instance.FlowStateName = FlowStatus.FiniShed.GetDescription();
                    }
                    else
                    {
                        instance.NextNodeNo = setting.NodeNo;
                        instance.NextNodeName = setting.NodeName;
                        instance.NextOperatorId = setting.UserId;
                        instance.NextOperatorName = setting.UserNickname;
                    }
                    instance.UpdateTime = now;
                    await instanceRep.UpdateAsync(instance);

                    #endregion 添加记录
                    WF_Record record = new WF_Record();
                    record.RecordId = instance.InstanceId;
                    record.InstanceId = instance.InstanceId;
                    record.NodeNo = instance.CurrentNodeNo;
                    record.NodeName = instance.CurrentNodeName;
                    record.OperatorId = instance.CurrentOperatorId;
                    record.OperatorName = instance.CurrentOperatorName;
                    record.ApproveStatus = request.ApproveStatus;
                    //把整数转成枚举
                    record.ApproveStatusName = ((ApproveStatus)request.ApproveStatus).GetDescription();
                    record.OperatorOpinion = request.OperatorOpinion;
                    record.CreateTime = now;
                    await recordRep.UpdateAsync(record);

                    #region 添加记录
                    #endregion 

                    tran.Commit();
                }
                catch (Exception ex)
                {
                    result.code = ApiEnum.UpdateFail;
                    result.message = ApiEnum.UpdateFail.GetDescription() + "" + ex.Message;

                    logger.LogError("代办审批报错:"+ex.Message);
                    tran.Rollback();
                }
            }

                return await Task.FromResult(result);
        }
    }
}
